package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import bean.UserBean;

public class RegisterDao {
	public int register(String name, String password, String dormitory, String telephone) throws ClassNotFoundException, SQLException {
		Connection conn = DBUtil.getConnection();
		PreparedStatement ps1 = conn.prepareStatement("select * from user where username=?");
		PreparedStatement ps2=null;
		ResultSet result2=null;
		PreparedStatement ps3=null;
		ps1.setString(1, name);
		
		int res=-1;
		ResultSet result1 = ps1.executeQuery();
		if(result1.next()) {
			res = 1;
		}
		else {
			ps2 = conn.prepareStatement("select * from dormitory where dormitoryname=?");
			ps2.setString(1, dormitory);

			result2 = ps2.executeQuery();
			if(!result2.next()) {
				ps2.close();
				result2.close();
				res = 3;
			}
			else {
				int dormitoryId = result2.getInt(1);
				ps3 = conn.prepareStatement("insert into user(username,userpassword,telephone,dormitoryid) values(?,?,?,?)");
				ps3.setString(1,name);
				ps3.setString(2,password);
				ps3.setString(3,telephone);
				ps3.setInt(4,dormitoryId);
				ps3.executeUpdate();
				res = 0;
			}
		}
		ps1.close();
		result1.close();
		if(ps2!=null)
			ps2.close();
		if(result2!=null)
			result2.close();
		if(ps3!=null)
			ps3.cancel();
		conn.close();
		System.out.println(res);
		return res;
	}
}
